package com.bw.lib_log.file

import java.io.*
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.locks.ReentrantLock

class LogFileManager(private val logDir: File) {

    companion object {
        private const val MAX_FILE_COUNT = 10
        private const val MAX_FILE_SIZE = 30 * 1024 * 1024 // 30MB
        private val FILE_NAME_FORMAT = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
        private val LOG_ENTRY_FORMAT = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault())
    }

    private val lock = ReentrantLock()
    private var currentLogFile: File? = null
    private var currentFileSize: Long = 0

    init {
        if (!logDir.exists()) {
            logDir.mkdirs()
        }
        cleanOldLogs()
        initCurrentFile()
    }

    /**
     * 写入日志到文件
     * @param content 日志内容（不包含换行符）
     * @return 写入是否成功
     */
    fun writeLog(content: String): Boolean {
        lock.lock()
        try {
            val logEntry = "${LOG_ENTRY_FORMAT.format(Date())} $content\n"
            val bytes = logEntry.toByteArray()

            // 检查文件大小
            if (currentFileSize + bytes.size > MAX_FILE_SIZE) {
                rotateLogFile()
            }

            return try {
                FileOutputStream(currentLogFile, true).use { fos ->
                    fos.write(bytes)
                    fos.flush()
                }
                currentFileSize += bytes.size
                true
            } catch (e: IOException) {
                e.printStackTrace()
                false
            }
        } finally {
            lock.unlock()
        }
    }

    /**
     * 获取所有日志文件（按时间倒序，最新的在前）
     */
    fun getAllLogFiles(): List<File> {
        lock.lock()
        try {
            return logDir.listFiles { file ->
                file.isFile && file.name.startsWith("log_") && file.name.endsWith(".txt")
            }?.sortedByDescending { it.name } ?: emptyList()
        } finally {
            lock.unlock()
        }
    }

    /**
     * 删除所有日志文件
     */
    fun clearAllLogs(): Boolean {
        lock.lock()
        try {
            return getAllLogFiles().all { it.delete() }.also {
                initCurrentFile() // 重新初始化当前文件
            }
        } finally {
            lock.unlock()
        }
    }

    /**
     * 获取当前日志文件路径
     */
    fun getCurrentLogFilePath(): String? {
        return currentLogFile?.absolutePath
    }

    /**
     * 获取当前日志文件大小（字节）
     */
    fun getCurrentLogFileSize(): Long {
        return currentFileSize
    }

    // ============ 私有方法 ============

    private fun initCurrentFile() {
        val files = getAllLogFiles()
        currentLogFile = if (files.isNotEmpty()) {
            files.first().also {
                currentFileSize = it.length()
            }
        } else {
            createNewLogFile()
        }
    }

    private fun rotateLogFile() {
        cleanOldLogs()
        currentLogFile = createNewLogFile()
        currentFileSize = 0
    }

    private fun createNewLogFile(): File {
        val newFile = File(logDir, "log_${FILE_NAME_FORMAT.format(Date())}.txt")
        newFile.createNewFile()
        return newFile
    }

    private fun cleanOldLogs() {
        val files = getAllLogFiles()
        if (files.size >= MAX_FILE_COUNT) {
            files.subList(MAX_FILE_COUNT - 1, files.size).forEach {
                it.delete()
            }
        }
    }
}